package com.mzj.solr;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.CursorMarkParams;

public class SolrCursorQuery {

	private static final Logger LOG = Logger.getLogger(SolrCursorQuery.class);  
	
	// 游标查询
	public static void cursorQuery(SolrClient client ,SolrClient cloudClient, String indexName) throws Exception {
		// solr查询封装
		SolrQuery sq = new SolrQuery();
		sq.setRows(10000);// 设置游标一次读的数量
		sq.set("q", "*:*");// 按条件检索
		sq.setSort("id", ORDER.asc);// 根据主键排序
		String cursorMark = CursorMarkParams.CURSOR_MARK_START;// 游标初始化
		boolean done = false;
		List<SolrInputDocument> inpList = null;
		int i =1;
		while (!done) {
			sq.set(CursorMarkParams.CURSOR_MARK_PARAM, cursorMark);// 变化游标条件
			QueryResponse rsp = client.query(sq);// 执行多次查询读取
			String nextCursorMark = rsp.getNextCursorMark();// 获取下次游标
			
			try {
				// 做一些操作数据的事
				inpList = new ArrayList<SolrInputDocument>();
				for (SolrDocument sd : rsp.getResults()) {
					try {
						String id = (String) sd.get("id");
						LOG.info("--------------cursorQuery:"+i+", id:"+id);
						
						SolrDocument doc = client.getById(id);
						Collection<String> ks = doc.getFieldNames();
			        	SolrInputDocument input = new SolrInputDocument();
			        	for (String k : ks) {
			        		if(!"_version_".equals(k)){
			        			input.addField(k, doc.getFieldValue(k));
			        		}
			        	}  
			        	inpList.add(input);
			        	i++;
					}catch(Exception e) {
						LOG.error(e.getMessage(),e);
					}
				}
				cloudClient.add(indexName,inpList);
		        cloudClient.commit(indexName);
			}catch(Exception e) {
				LOG.error(e.getMessage(),e);
			}
			// 如果两次游标一样，说明数据拉取完毕，可以结束循环了
			if (cursorMark.equals(nextCursorMark)) {
				done = true;
			}
			cursorMark = nextCursorMark;
		}
	}
}
